package http_utils

import (
	"io/ioutil"
	"net/http"
	"net/url"
)

// Get get请求
func Get(urlStr string, params map[string]string) (string, error) {
	urlParams := make(url.Values)
	for key, v := range params {
		urlParams.Set(key, v)
	}
	Url, err := url.Parse(urlStr)
	if err != nil {
		return "", err
	}
	Url.RawQuery = urlParams.Encode()
	urlPath := Url.String()
	response, err := http.Get(urlPath)
	if err != nil {
		return "", err
	}
	defer func() {
		if response != nil && response.Body != nil {
			response.Body.Close()
		}
	}()
	all, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	return string(all), nil
}

// Post post请求
func Post(urlStr string, params map[string]string) (string, error) {
	urlParams := make(url.Values)
	for key, v := range params {
		urlParams.Set(key, v)
	}
	response, err := http.PostForm(urlStr, urlParams)
	if err != nil {
		return "", err
	}
	defer func() {
		if response != nil && response.Body != nil {
			response.Body.Close()
		}
	}()
	all, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	return string(all), nil
}
